// created by noellynch
// Jun 4, 2009

package com.sceneworker.editors.glslshadereditor.uniformreps;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.concurrent.Callable;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JTextField;

import net.miginfocom.swing.MigLayout;

import com.jme.scene.state.GLSLShaderObjectsState;
import com.jme.util.GameTaskQueueManager;
import com.jme.util.shader.ShaderVariable;
import com.myjavautils.swing.MigLayoutUtils;
import com.myjavautils.swing.SimpleAlert;
import com.myjavautils.swing.SwingComponentFactory;
import com.sceneworker.editors.glslshadereditor.UniformRepresentations;
import com.sceneworker.editors.glslshadereditor.UniformsPanel;
import com.sceneworker.editors.glslshadereditor.UniformRepresentations.IUniformRepresentation;

public class EditUniformPanel extends JPanel {

	public	EditUniformPanel(final GLSLShaderObjectsState cl_shaderState, final ShaderVariable cl_var, final JDialog cl_par, final UniformsPanel cl_panel) {
		setLayout(new MigLayout());
		
		// get the ui rep for this shader variable type
		final	IUniformRepresentation		lcl_rep = UniformRepresentations.getRepresentationByClass(cl_var.getClass());
		if(lcl_rep == null) {
			SimpleAlert.doAlert("Could not find a UI to represent this uniform.", this);
			cl_par.setVisible(false);
			return;
		}
		
		final	ArrayList<JTextField>	lcla_valueFields = lcl_rep.getUIRep(cl_var, this);
		
		JButton		lcl_update = SwingComponentFactory.makeAButton("Update");
		lcl_update.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				updateUniform(lcla_valueFields, lcl_rep, cl_var, cl_panel, cl_shaderState);
				cl_par.setVisible(false);
			}
		});
		
		JButton		lcl_cancel = SwingComponentFactory.makeAButton("Cancel");
		lcl_cancel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				cl_par.setVisible(false);
			}
		});
		
		MigLayoutUtils.makeRightAlignedButtonBar(this, lcl_update, lcl_cancel);
	}
	
	private	void	updateUniform(final ArrayList<JTextField> cla_valueFields, final IUniformRepresentation cl_rep, final ShaderVariable cl_var, 
			final UniformsPanel cl_panel, final GLSLShaderObjectsState cl_shaderState) {
		GameTaskQueueManager.getManager().update(new Callable<Void>() {
			public Void call() throws Exception {
				cl_rep.updateFromUI(cl_shaderState, cla_valueFields, cl_var);
				cl_panel.updateUniformValueField();
				return null;
			}
		});
	}
}
